<template>
  <navigation></navigation>
  <div class="bg-gradient-to-br from-gray-50 to-blue-50/30 min-h-screen py-12">
    <div class="max-w-5xl mx-auto px-4 sm:px-6 lg:px-8">
      <!-- 头部导航 -->
      <div class="flex items-center justify-between mb-8">
        <h1 class="text-2xl font-bold text-gray-800">个人信息管理</h1>
        <button 
          @click="personalCenter"
          class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
        >
          返回个人中心
        </button>
      </div>

      <!-- 主内容区 -->
      <div class="bg-white rounded-xl shadow-lg p-8">
        <div class="flex flex-col lg:flex-row gap-8">
          <!-- 头像上传区 -->
          <div class="flex flex-col items-center w-full lg:w-1/3">
            <div 
              class="relative w-48 h-48 rounded-full cursor-pointer group"
              @click="triggerFileUpload"
            >
              <img 
                :src="avatarPreview || form.userImg"
                class="w-full h-full object-cover rounded-full border-4 border-white shadow-lg transition-all duration-300 group-hover:scale-105"
                alt="用户头像"
              />
              <div class="absolute inset-0 bg-black/50 flex flex-col items-center justify-center rounded-full opacity-0 transition-opacity duration-300 group-hover:opacity-100">
                <svg class="w-8 h-8 text-white mb-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 9a2 2 0 012-2h.93a2 2 0 001.664-.89l.812-1.22A2 2 0 0110.07 4h3.86a2 2 0 011.664.89l.812 1.22A2 2 0 0018.07 7H19a2 2 0 012 2v9a2 2 0 01-2 2H5a2 2 0 01-2-2V9z"/>
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 13a3 3 0 11-6 0 3 3 0 016 0z"/>
                </svg>
                <span class="text-white text-sm">点击修改头像</span>
              </div>
              <input 
                type="file"
                ref="fileInput"
                accept="image/*"
                class="hidden"
                @change="handleFileUpload"
              />
            </div>
            
            <button 
              @click="uploadAvatar"
              :disabled="uploading"
              class="mt-4 px-6 py-2 bg-green-500 text-white rounded-lg hover:bg-green-600 transition-colors disabled:opacity-50"
            >
              {{ uploading ? '上传中...' : '保存头像' }}
            </button>
          </div>

          <!-- 表单区 -->
          <form class="flex-1 space-y-6" @submit.prevent="submitForm">
            <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
              <!-- 姓名 -->
              <div class="space-y-2">
                <label class="block text-gray-700 font-medium">姓名</label>
                <div class="relative">
                  <img src="/src/assets/img/姓名.png" class="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5">
                  <input
                    v-model="form.name"
                    type="text"
                    class="w-full pl-10 pr-4 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                    placeholder="请输入姓名"
                  >
                </div>
              </div>

              <!-- 学号 -->
              <div class="space-y-2">
                <label class="block text-gray-700 font-medium">学号</label>
                <div class="relative">
                  <img src="/src/assets/img/学号.svg" class="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5">
                  <input
                    v-model="form.studentId"
                    type="text"
                    class="w-full pl-10 pr-4 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                    placeholder="请输入学号"
                    disabled
                  >
                </div>
              </div>

              <!-- 学院 -->
              <div class="space-y-2">
                <label class="block text-gray-700 font-medium">学院</label>
                <div class="relative">
                  <img src="/src/assets/img/学院.svg" class="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5">
                  <select 
                    v-model="form.college"
                    class="w-full pl-10 pr-4 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 appearance-none"
                  >
                    <option value="">请选择学院</option>
                    <option>计算机科学与技术学院</option>
                    <option>电子信息工程学院</option>
                    <option>机械工程学院</option>
                  </select>
                </div>
              </div>

              <!-- 专业 -->
              <div class="space-y-2">
                <label class="block text-gray-700 font-medium">专业</label>
                <div class="relative">
                  <img src="/src/assets/img/专业.svg" class="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5">
                  <input
                    v-model="form.major"
                    type="text"
                    class="w-full pl-10 pr-4 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                    placeholder="请输入专业"
                  >
                </div>
              </div>

              <!-- 邮箱 -->
              <div class="space-y-2">
                <label class="block text-gray-700 font-medium">邮箱</label>
                <div class="relative">
                  <img src="/src/assets/img/邮箱.svg" class="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5">
                  <input
                    v-model="form.email"
                    type="email"
                    class="w-full pl-10 pr-4 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                    placeholder="example@university.com"
                  >
                </div>
              </div>

              <!-- 意向岗位 -->
              <div class="space-y-2">
                <label class="block text-gray-700 font-medium">意向岗位</label>
                <div class="relative">
                  <img src="/src/assets/img/岗位管理.svg" class="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5">
                  <select 
                    v-model="form.position"
                    class="w-full pl-10 pr-4 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 appearance-none"
                  >
                    <option value="">请选择岗位</option>
                    <option>前端开发工程师</option>
                    <option>Java后端开发</option>
                    <option>UI/UX设计师</option>
                  </select>
                </div>
              </div>
            </div>

            <!-- 操作按钮 -->
            <div class="flex gap-4 pt-8">
              <button
                type="button"
                @click="resetForm"
                class="flex-1 px-4 py-2 bg-gray-500 text-white rounded-lg hover:bg-gray-600 transition-colors"
              >
                重置信息
              </button>
              <button
                type="submit"
                class="flex-1 px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
              >
                保存修改
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'
import { getToken } from '@/utils/auth'

// 默认头像
const defaultAvatar = '/src/assets/default-avatar.png'

// 表单数据
const form = reactive({
  name: '罗峰',
  studentId: '202010101',
  college: '计算机科学与技术学院',
  major: '软件工程',
  email: 'luofeng@university.com',
  position: '前端开发工程师',
  userImg: defaultAvatar
})

// 头像上传相关
const fileInput = ref(null)
const avatarPreview = ref('')
const selectedFile = ref(null)
const uploading = ref(false)

// 触发文件选择
const triggerFileUpload = () => {
  fileInput.value.click()
}

// 处理文件上传
const handleFileUpload = async (event) => {
  const file = event.target.files[0]
  if (!file) return

  // 文件验证
  if (!file.type.startsWith('image/')) {
    ElMessage.error('仅支持图片格式（JPEG/PNG）')
    return
  }

  if (file.size > 5 * 1024 * 1024) {
    ElMessage.error('图片大小不能超过5MB')
    return
  }

  // 预览图片
  const reader = new FileReader()
  reader.onload = (e) => {
    avatarPreview.value = e.target.result
  }
  reader.readAsDataURL(file)
  selectedFile.value = file
}

// 上传头像
const uploadAvatar = async () => {
  if (!selectedFile.value) {
    ElMessage.warning('请选择要上传的头像')
    return
  }

  try {
    uploading.value = true
    const formData = new FormData()
    formData.append('avatar', selectedFile.value)

    const response = await axios.post('/api/upload-avatar', formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
        'Authorization': `Bearer ${getToken()}`
      }
    })

    form.userImg = response.data.url
    ElMessage.success('头像更新成功')
  } catch (error) {
    ElMessage.error('头像上传失败')
    console.error('上传错误:', error)
  } finally {
    uploading.value = false
    selectedFile.value = null
  }
}

// 提交表单
const submitForm = async () => {
  try {
    const payload = {
      ...form,
      avatar: form.userImg
    }

    const response = await axios.patch('/api/profile', payload, {
      headers: {
        'Authorization': `Bearer ${getToken()}`
      }
    })

    if (response.data.code === 200) {
      ElMessage.success('个人信息已更新')
    }
  } catch (error) {
    ElMessage.error('保存失败')
    console.error('保存错误:', error)
  }
}

// 重置表单
const resetForm = () => {
  Object.assign(form, {
    name: '罗峰',
    studentId: '202010101',
    college: '计算机科学与技术学院',
    major: '软件工程',
    email: 'luofeng@university.com',
    position: '前端开发工程师',
    userImg: defaultAvatar
  })
  avatarPreview.value = ''
  ElMessage.info('已重置所有信息')
}

// 返回个人中心
const personalCenter = () => {
  window.history.back()
}
</script>

<style scoped>
/* 自定义加载动画 */
@keyframes spin {
  to { transform: rotate(360deg); }
}

.animate-spin {
  animation: spin 1s linear infinite;
}

/* 下拉箭头样式 */
select {
  background-image: url("data:image/svg+xml;charset=UTF-8,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='currentColor' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3e%3cpolyline points='6 9 12 15 18 9'%3e%3c/polyline%3e%3c/svg%3e");
  background-repeat: no-repeat;
  background-position: right 1rem center;
  background-size: 1em;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .grid-cols-2 {
    grid-template-columns: 1fr;
  }
  
  .flex-col.lg\:flex-row {
    flex-direction: column;
  }
  
  .w-full.lg\:w-1\/3 {
    width: 100%;
    margin-bottom: 2rem;
  }
}

/* 头像悬停效果 */
.group:hover .group-hover\:scale-105 {
  transform: scale(1.05);
  transition: transform 0.3s ease;
}

/* 按钮过渡效果 */
.transition-colors {
  transition: background-color 0.3s ease;
}
</style>